package com.myblog.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.myblog.constant.RedisHashKey;
import com.myblog.constant.RedisKey;
import com.myblog.mapper.VisitorMapper;
import com.myblog.model.Visitor;
import com.myblog.service.VisitorService;
import com.myblog.utils.DataMap;
import com.myblog.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 页面访客量的service
 */
@Service
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    RedisServiceImpl redisServiceImpl;

    @Autowired
    private VisitorMapper visitorMapper;

    @Override
    public DataMap getVisitorNumByPageName(String pageName, HttpServletRequest request) {
        //查询redis中总访客量
        Object totalVisitorNum =  redisServiceImpl.getHash(RedisKey.VISITOR, RedisHashKey.TOTAL_VISITOR);
        //判断数据是否为空，如果为空调用函数进行处理
        Visitor totalVisitor = redisServiceImpl.visitorMsgIfExist(totalVisitorNum, RedisHashKey.TOTAL_VISITOR);

        //判断pageName是否含有article
        if(pageName.contains("article")){
            //如果含有"article"
            Object visitorNum = redisServiceImpl.getHash(RedisKey.VISITOR ,pageName);
            //判断数据是否为空，如果为空调用函数进行处理
            Visitor visitor = redisServiceImpl.visitorMsgIfExist(visitorNum, pageName);
            //更新访问量
            redisServiceImpl.updateVisitorNum(visitor,totalVisitor);

            //封装数据
            JSONObject result = new JSONObject();
            result.put(RedisHashKey.TOTAL_VISITOR,totalVisitor.getVisitorNum());
            result.put("pageVisitor",visitor.getVisitorNum());

            return DataMap.success().setData(result);
        }
        //如果不含有"article"，则归入“visitorVolume”
        //查询redis中是否有visitorVolume键值对
        Object visitorNum =  redisServiceImpl.getHash(RedisKey.VISITOR ,RedisHashKey.VOLUME_VISITOR);
        //判断数据是否为空，如果为空，调用函数进行处理
        Visitor volumeVisitor = redisServiceImpl.visitorMsgIfExist(visitorNum, RedisHashKey.VOLUME_VISITOR);

        //更新访客量，当前页面和总页面的访客量+1
        redisServiceImpl.updateVisitorNum(volumeVisitor,totalVisitor);

        JSONObject result = new JSONObject();
        result.put(RedisHashKey.TOTAL_VISITOR,totalVisitor.getVisitorNum());
        result.put("pageVisitor",volumeVisitor.getVisitorNum());

        return DataMap.success().setData(result);
    }


}
